from  flask import Flask,request,jsonify
from flask_sqlalchemy import SQLAlchemy
from conf import Config
from flask_cors import CORS
import json

#初始实例对象
app = Flask(__name__)

#导入Config
app.config.from_object(Config)
#配置跨域
CORS(app)
#构造数据库
db = SQLAlchemy(app)

class Order(db.Model):
    __tablename__='order'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(20),default='')
    price = db.Column(db.Float(7,2),default=0)

class Redis(db.Model):
    __tablename__='redis'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    key = db.Column(db.String(20),default='')
    value = db.Column(db.Integer,default=0)


# db.create_all()

@app.route('/order',methods=['POST','GET','DELETE'])
def order():
    if request.method == 'POST':
        data = json.loads(request.data)
        name = data['name']
        price = data['price']
        order = Order(name=name,price=price)
        db.session.add(order)
        db.session.commit()
        return jsonify({"code":200})
    elif request.method == 'GET':
        res = Order.query.all()
        list1 = []
        for i in res:
            dict1 = {}
            dict1['id'] = i.id
            dict1['name'] = i.name
            dict1['price'] = float(i.price)*0.8
            list1.append(dict1)
        return jsonify({"code":200,'list':list1})
    elif request.method == 'DELETE':
        id = request.args.get('id')
        order = Order.query.filter_by(id=id).delete()
        db.session.commit()
        return jsonify({'code':200})

# @app.after_request
# def after():
#     redis = Redis(key='qwer',value=12345)
#     db.session.add(redis)
#     db.session.commit()
#     return 'ok'
    
        

if __name__ == '__main__':
    app.run()